﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;


/** 
 ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** **
 * Description: 
 * Author: Heller (HellerSong@outlook.com)
 * CreationTime: 4/3/2015 10:44:35 PM
 ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** ** 
 **/
namespace DevLib.FileTool
{
	public class IniHelper
	{
		/* Demo template of ini file
         * 
         * ; means notation
         * [Section Name1]
         * name1 = value1
         * name2 = value2
         * 
         * [Section Name2]
         * name1 = value1
         * name2 = value2
         * name3 = value3
         */

		[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileString", CharSet = CharSet.Unicode)]
		public static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

		[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSectionNames", CharSet = CharSet.Unicode)]
		public static extern int GetPrivateProfileSectionNames(IntPtr lpszReturnBuffer, int nSize, string filePath);

		[DllImport("kernel32.dll", EntryPoint = "GetPrivateProfileSection", CharSet = CharSet.Unicode)]
		public static extern int GetPrivateProfileSection(string lpAppName, byte[] lpReturnedString, int nSize, string filePath);
		
		[DllImport("kernel32.dll", EntryPoint = "WritePrivateProfileString", CharSet = CharSet.Unicode)]
		public static extern long WritePrivateProfileString(string section, string key, string val, string filePath);



		public static String GetKeyValueBySection(String iniFilePath, String section, String key)
		{
			StringBuilder value = new StringBuilder(255);
			GetPrivateProfileString(section, key, "", value, 255, iniFilePath);

			return value.ToString();
		}

		public static void WriteKeyValueBySection(String iniFilePath, String section, String key, String value)
		{
			WritePrivateProfileString(section, key, value, iniFilePath);
		}

		public static String[] GetAllSectionsName(String iniFilePath)
		{
			int MAX_BUFFER = 32767;
			String[] sectionsNameArray;
			IntPtr pReturnedString = Marshal.AllocCoTaskMem(MAX_BUFFER);
			int bytesReturned = GetPrivateProfileSectionNames(pReturnedString, MAX_BUFFER, iniFilePath);
			if (bytesReturned == 0)
			{
				return sectionsNameArray = null;
			}
			String local = Marshal.PtrToStringAnsi(pReturnedString, (int)bytesReturned).ToString();
			Marshal.FreeCoTaskMem(pReturnedString);
			// Use of substring below removes terminating null for split
			sectionsNameArray = local.Substring(0, local.Length - 1).Split('\0');

			return sectionsNameArray;
		}


	}
}
